package com.ctrip.ec.api.admin.controller.area;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.biz.dao.area.AreaDao;
import com.ctrip.ec.biz.entity.area.AreaEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
@RestController
@RequestMapping("area")
public class AreaController{
    @Autowired
    private AreaDao area;

    @GetMapping("list")
    public List<AreaEntity> list(@RequestParam(required = false) Long parentId) throws SQLException {
        String where = null;
        if(parentId != null) {
            if (parentId == 0) {
                where = " id like '__0000'";
            } else {
                char[] arrParentId = parentId.toString().toCharArray();
                int length = arrParentId.length;//去掉0后的长度
                for (int i = arrParentId.length - 1; i >= 0; i--) {
                    if (arrParentId[i] == '0') {
                        length--;
                    } else {
                        break;
                    }
                }
                where = "id like '" + parentId.toString().substring(0, length) + "%' and id !=" + parentId;
            }
        }
        List<AreaEntity> list = area.list(where);
        return list;
    }

    @PostMapping("list")
    public List<AreaEntity> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<AreaEntity> list = area.list(setting);
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }

    @GetMapping("detail/{id}")
    public  AreaEntity detail(@PathVariable Long id) throws SQLException {
        return area.entity(id);
    }

    @PostMapping("save")
    public  Integer save(@RequestBody AreaEntity entity) throws SQLException {
        area.save(entity);
        return entity.getId();
    }

    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        area.delete(ids);
    }
    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        area.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        area.unerase(ids);
    }
}
